package com.ellecity06.cwhiskymall.ui.share.poster

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.*
import com.ellecity06.common.utils.*
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.adapter.PosterImageAdapter
import com.ellecity06.cwhiskymall.adapter.ShareGoodImageAdapter
import com.ellecity06.cwhiskymall.databinding.ActivitySharePosterBinding
import com.ellecity06.cwhiskymall.helper.ShareHelper
import com.ellecity06.cwhiskymall.storage.UserStorage
import com.ellecity06.cwhiskymall.view.dialog.DownLoadImageDialog

/**
 * @author ellecity06
 * @time 2024/11/4 10:52
 * @des 海报分享页面
 */
class SharePosterActivity : BaseMvvmActivity<ActivitySharePosterBinding, SharePosterViewModel>(),
    View.OnClickListener {
    private val goodId: Int by lazy { intent.getIntExtra("good_id", 0) }
    private val adapter: ShareGoodImageAdapter by lazy { ShareGoodImageAdapter() }
    private val posterAdapter: PosterImageAdapter by lazy { PosterImageAdapter() }
    override fun inflateBinding(): ActivitySharePosterBinding {
        return ActivitySharePosterBinding.inflate(layoutInflater)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        title = "分享商品"
        initView()
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(SharePosterIntent.FetchGoodDetail(goodId))
        }
    }

    override fun initEvent() {
        binding.tvSelectAll.setOnClickListener(this)
        binding.tvCopy.setOnClickListener(this)
        binding.layoutWx.setOnClickListener(this)
        binding.layoutCopy.setOnClickListener(this)
        binding.layoutSave.setOnClickListener(this)
    }
private var shareUrl:String? = null
    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is SharePosterState.GoodImageSuccess -> {
                    adapter.submitList(it.list)
                    setSelectCount()
                    binding.tvTotalCount.text = "${it.list.size}"
                    handlePosterGood()
                }
                is SharePosterState.GoodDesc -> {
                    binding.tvCopywriter.text = it.str
                }
                is SharePosterState.GoodDetail -> {
                    setPosterData(it)
                }
                is SharePosterState.H5Url -> {
                    shareUrl=
                        "${it.url}/#/Register?activityId=1002&invitationCode=${UserStorage.user?.shardCode}"
                    setQrCode(shareUrl!!)

                }
            }
        }
    }

    private fun setQrCode(url: String) {
        val createQrBitmap = BitmapUtils.createQrBitmap(url, 105f)
        logD("url=$url")
        binding.ivQrCode.setImageBitmap(createQrBitmap)
    }

    /**
     * 设置分享海报数据
     */
    private fun setPosterData(it: SharePosterState.GoodDetail) {
        binding.tvGoodName.text = it.data.spuName
        binding.tvPrice.text = "到手价￥${it.data.salesPrice}元"
        binding.tvGiftAmount.text = "赠送${it.data.contribution}贡献金"
        handlePosterGood()
    }

    private fun handlePosterGood() {
        val selectList = adapter.getSelectList()
        if (selectList.isNotEmpty()) {
            when (selectList.size) {
                1 -> {
                    binding.rvMultipleGood.visibility = View.GONE
                    binding.ivSingle.visibility = View.VISIBLE
                    binding.ivSingle.load(this, selectList[0].image)
                }
                2 -> {
                    binding.rvMultipleGood.visibility = View.VISIBLE
                    binding.ivSingle.visibility = View.GONE
                    binding.rvMultipleGood.layoutManager = GridLayoutManager(this, 2)
                    binding.rvMultipleGood.addGridDecoration(size = R.dimen.dp_5)
                    binding.rvMultipleGood.adapter = posterAdapter
                    posterAdapter.submitList(selectList)

                }
                else -> {
                    binding.rvMultipleGood.visibility = View.VISIBLE
                    binding.ivSingle.visibility = View.GONE
                    binding.rvMultipleGood.layoutManager = GridLayoutManager(this, 3)
                    binding.rvMultipleGood.addGridDecoration(size = R.dimen.dp_5)
                    binding.rvMultipleGood.adapter = posterAdapter
                    posterAdapter.submitList(selectList)
                }
            }

        }
    }

    private fun setSelectCount() {
        binding.tvSelectCount.text = "${adapter.getSelectList().size}"
    }

    private fun initView() {
        binding.rvImage.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        binding.rvImage.addLinearDecoration(R.dimen.dp_5)
        binding.rvImage.clearAnimations()
        binding.rvImage.adapter = adapter
        adapter.setOnItemClickListener { _, view, position ->
            adapter.check(position)
            setSelectCount()
            handlePosterGood()

        }


    }

    override fun onClick(view: View?) {
        when (view?.id) {
            binding.tvSelectAll.id -> {
                adapter.selectAll()
                setSelectCount()
            }
            binding.tvCopy.id -> {
                CommonUtils.copyStr(this, binding.tvCopywriter.text.toString())
                ToastUtils.show(R.string.text_copy_success.stringResToString())
            }
            binding.layoutWx.id -> {
                val selectList = adapter.getSelectList()
                if (selectList.isEmpty()) {
                    ToastUtils.show("至少选择一个张图片")
                    return
                }
                shareToImage()


            }
            binding.layoutCopy.id -> {
                CommonUtils.copyStr(this, shareUrl)
                ToastUtils.show(R.string.text_copy_link_success.stringResToString())
            }

            binding.layoutSave.id -> {
                val selectList = adapter.getSelectList()
                if (selectList.isEmpty()) {
                    ToastUtils.show("至少选择一个张图片")
                    return
                }
                requestStorePermission("保存需要手机储存权限") { allGranted, grantedList, deniedList ->
                    val list = selectList.map { it.image!! }.toList()
                    DownLoadImageDialog(this, list).show()
                }

            }
        }
    }

    private fun shareToImage() {
        requestStorePermission("分享图片到微信需要手机存储权限") { allGranted, grantedList, deniedList ->
            val createBitmapFromView =
                BitmapUtils.createBitmapFromView(binding.layoutPoster)
            if (createBitmapFromView != null) {
                ShareHelper.shareImageToWx(createBitmapFromView) {}
//                        FileUtil.saveImageFileToExternal(this,FileUtil.getRandomImageName(), imageBitmap = createBitmapFromView)
            }

//                        ShareHelper.shareImageToSystem(this, createBitmapFromView, null)
//                        ShareHelper.shareWechatPic(createBitmapFromView)

        }
    }
}